<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class km_barang extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('km_barang_model', 'Barang');
		$this->load->model('combo_model', 'Combo');
		$this->load->model('mis_turnover/sample_master_model', 'Master');
		$this->load->model('km_mdstruktur_model', 'Mdstruktur');
		$this->secure_session();
	}
	
	function index(){
		$data['title'] = "Setup Barang";
		$data['combodiv'] = $this->Mdstruktur->getDiv();

		$data['combodep'] = $this->Mdstruktur->getDep(0);
		$combokemasan = $this->Barang->getCombo('KM_KEMASAN', 'KEMASAN_ID', 'KEMASAN_NAMA');
		$combosatuan = $this->Barang->getCombo('KM_SATUAN', 'SATUAN_ID', 'SATUAN_NAMA');
		$data['combokemasan'] = $combokemasan;
		$data['combosatuan'] = $combosatuan;
		// Define Combo Data
		$data['arr_application']	= $this->Combo->ITApplication();
		
		viewByTemplate('km_barang/index', $data, 'grid');
	}
	
	function getdata()
	{
		$this->secure_session();
		echo $this->Barang->GetJSON();
	}

	function getdata_ac($kode=null)
	{
		$this->secure_session();

		echo $this->Barang->GetJSON_ac($kode);
	}

	function getdatabyvendor()
	{
		$this->secure_session();
		echo $this->Barang->GetJSONByVendor(get('kd_vendor'));
	}

	function getDepartemen($type=null){
		echo $this->Mdstruktur->getDep($this->input->post('option'));
	}

	function getClass($type=null){
		echo $this->Mdstruktur->getCls($this->input->post('option'));
	}

	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");


		//barang_barcode, barang_kode, barang_nama
		if (post("barang_kode") == '') {
			$error->Add("barang_kode", "Kode Barang", $tpl_empty);
		} else if (post("barang_nama") == '') {
			$error->Add("barang_nama", "Nama Barang", $tpl_empty);
		} else if (post("barang_barcode") == '') {
			$error->Add("barang_barcode", "Barcode Barang", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT 1 FROM km_barang WHERE barang_kode = '".@ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim(post("barang_kode"))))."'")) > 0) {
			$error->Add("barang_kode", "Kode Barang", $tpl_duplicate);
		}		
		return $error;
	}
	
	function ajax_post()
	{
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try
		{
			$data	= post_by_key(array('barang_id','mdstruktur_id_div','mdstruktur_id_dep','mdstruktur_id_cls','satuan_id','kemasan_id','barang_barcode','barang_kode','barang_nama','barang_nm','barang_ppn','barang_qty1','barang_hjual1','barang_margin1','barang_qty2','barang_hjual2','barang_margin2','barang_qty3, barang_hjual3, barang_margin3, barang_diskon, barang_hpokok, barang_stok_min','barang_stok_max','barang_image','barang_tipe','barang_limit_max, barang_limit_min, barang_keterangan','barang_status_aktif','satuan_id_besar','kemasan_id_besar','div','dep','cls','supp_id','barang_status_level','kms_karton','supplier','path','harga'));
				
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{

				$query = $this->db->query("SELECT barang_id FROM (SELECT * FROM km_barang ORDER BY barang_id DESC) WHERE rownum <=1");
				if ($query->row_array()) {
					$getquery = $query->row_array();
					$rowcount = $getquery['barang_id'];
					$autonum = $rowcount + 1;
				} else {
					$autonum = 1;
				}	

				// Fill Post Data
				$data	=  array(
					'mdstruktur_id_div' => $this->input->post('mdstruktur_id_div'),
					'mdstruktur_id_dep' => $this->input->post('mdstruktur_id_dep'),
					'mdstruktur_id_cls' => $this->input->post('mdstruktur_id_cls'),
					'barang_barcode' => $this->input->post('barang_barcode'),
					'barang_kode' => $this->input->post('barang_kode'),
					'barang_tipe' => $this->input->post('barang_tipe'),
					'barang_status_aktif' => $this->input->post('barang_status_aktif'),
					'barang_nama' => $this->input->post('barang_nama'),
					'barang_nm' => $this->input->post('barang_nm'),
					'kemasan_id' => $this->input->post('kemasan_id'),
					'satuan_id' => $this->input->post('satuan_id'),
					'satuan_id_besar' => $this->input->post('satuan_id_besar'),
					'kemasan_id_besar' => $this->input->post('kemasan_id_besar'),
					'barang_hpokok' => $this->input->post('barang_hpokok'),
					'barang_keterangan' => $this->input->post('barang_keterangan'),
					'barang_qty1' => $this->input->post('barang_qty1'),
					'barang_margin1' => $this->input->post('barang_margin1'),
					'barang_hjual1' => $this->input->post('barang_hjual1'),
					'barang_qty2' => $this->input->post('barang_qty2'),
					'barang_hjual2' => $this->input->post('barang_hjual2'),
					'barang_margin2' => $this->input->post('barang_margin2'),
					'barang_qty3' => $this->input->post('barang_qty3'),
					'barang_margin3' => $this->input->post('barang_margin3'),
					'barang_hjual3' => $this->input->post('barang_hjual3'),
					'barang_stok_min' => $this->input->post('barang_stok_min'),
					'barang_stok_max' => $this->input->post('barang_stok_max'),
					'barang_tipe' => $this->input->post('barang_tipe'),
					'barang_limit_max' => $this->input->post('barang_limit_max'),
					'barang_limit_min' => $this->input->post('barang_limit_min'),
				);


				if (post("mode") == "create")
				{	
					$id = array('barang_id' => $autonum);
					$data = array_merge($id, $data);
					$this->Barang->Add($data);

					$ls_response = "Data Tersimpan";

				}
				else if (post("mode") == "edit")
				{
					
					$this->Barang->Update($data, $this->input->post('barang_id'));

					$ls_response = "Data Tersimpan [edited]";
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
			'fields'	=> $error->GetDictionary(),
			'msg'		=> $ls_response,
			'genid'		=> $ls_genid,
			'form_sender'=> post("form_sender"))
		));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$barang_kode	= get('barang_kode');
		
		if ($barang_kode != "")
		{
			// Delete Single
			$arr_rule	= array('barang_kode' => $barang_kode);
			$ls_result = $this->Barang->DeleteSingle($arr_rule);

		}
		else
		{
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('barang_kode' => $row['barang_kode']);
				$ls_result .= $this->Barang->DeleteSingle($arr_rule);
			}
		}
		echo $ls_result;
	}
	function cetak(){
		$as_pk_master	= get('kode_barang');
		
		if($as_pk_master!='' && $as_pk_master!=''){
			
			// Load FPDF
			$this->load->helper('fpdf');
			
			// Set Data
			$data['data']			= $this->Master->GetSingleView($as_pk_master);
			//$data['arr_detail1']	= $this->Detail1->GetDetailByID($as_pk_master);
			//$data['arr_detail2']	= $this->Detail2->GetDetailByID($as_pk_master);
			
			// Load View
			$this->load->view('mis_laporan_perangkat/cetak', $data);
			
		}
	}

	function print_excel()
	{
		
		$x=0;

		$data_p = $this->Master->GetForExcel();

		$date = date('Y-m-d');

		//load our new PHPExcel library
		$this->load->library('excel');
		//activate worksheet number 1
		$this->excel->setActiveSheetIndex(0);
		//name the worksheet
		$this->excel->getActiveSheet()->setTitle("Laporan Perangkat_".$date);

		$no = 1;

			
		if ($data_p) {

			$styleArrayBorder = array(
				'borders' => array(
					'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN
					)
				)
			);

			$this->excel->getActiveSheet()->setCellValue('B8', 'NO');
			$this->excel->getActiveSheet()->setCellValue('C8', 'KODE BARANG');
			$this->excel->getActiveSheet()->setCellValue('D8', 'NAMA BARANG');
			$this->excel->getActiveSheet()->setCellValue('E8', 'NAMA MERK');
			$this->excel->getActiveSheet()->setCellValue('F8', 'SPESIFIKASI');
			$this->excel->getActiveSheet()->setCellValue('G8', 'KONDISI BARANG');
			$this->excel->getActiveSheet()->setCellValue('H8', 'TIPE');
			$this->excel->getActiveSheet()->setCellValue('I8', 'HARGA');
			$this->excel->getActiveSheet()->setCellValue('J8', 'JUMLAH');
			$this->excel->getActiveSheet()->setCellValue('K8', 'KETERANGAN');

			$this->excel->getActiveSheet()->getStyle('B8:K8')->getFont()->setBold(true);
			$this->excel->getActiveSheet()->getStyle('B8:K8')->getFill()->applyFromArray(array('type' => PHPExcel_Style_Fill::FILL_SOLID,'startcolor' => array('rgb' => 'EEEE11')));
			$this->excel->getActiveSheet()->getStyle('B8:K8')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

			$x = 8;

			for($i=0;$i<=$data_p['total']-1;$i++){
				$x++;

				$rows = $data_p['rows'];
				$rows2 = $rows[$i];

				$this->excel->getActiveSheet()->setCellValue('B'.$x, $no);
				$this->excel->getActiveSheet()->setCellValue('C'.$x, $rows2['kode_barang']);
				$this->excel->getActiveSheet()->setCellValue('D'.$x, $rows2['nama_barang']);
				$this->excel->getActiveSheet()->setCellValue('E'.$x, $rows2['nama_merek']);
				$this->excel->getActiveSheet()->setCellValue('F'.$x, $rows2['spesifikasi']);
				$this->excel->getActiveSheet()->setCellValue('G'.$x, $rows2['kondisi']);
				$this->excel->getActiveSheet()->setCellValue('H'.$x, $rows2['tipe']);
				$this->excel->getActiveSheet()->setCellValue('I'.$x, $rows2['harga']);
				$this->excel->getActiveSheet()->setCellValue('J'.$x, $rows2['jumlah']);
				$this->excel->getActiveSheet()->setCellValue('K'.$x, $rows2['keterangan']);

				$no++;
			}

			
		}

		$this->excel->getActiveSheet()->setCellValue('B4', strtoupper("Laporan Perangkat"));
		$this->excel->getActiveSheet()->setCellValue('B5', '('.$date.')');			

		$styleArray = array(
			'borders' => array(
			    'allborders' => array(
			    'style' => PHPExcel_Style_Border::BORDER_THIN
			    )
			),
			'font'  => array(
			    'size'  => 9,
			    'name'  => 'verdana'
			)
		);

		$this->excel->getActiveSheet()->getStyle('B8:K'.$x)->applyFromArray($styleArray);
		unset($styleArray);

		$styleArray1 = array(
		    'font'  => array(
		    'bold'  => true,
		    'uppercase' => true,
		    'size'  => 11,
		    'name'  => 'Calibri'
		    )
		);

		$this->excel->getActiveSheet()->getColumnDimension('C')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('D')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('G')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('I')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('K')->setWidth(22);
		

		$this->excel->getActiveSheet()->getStyle('D1:K'.$this->excel->getActiveSheet()->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00'); 

		$this->excel->getActiveSheet()->getStyle('C1:C'.$this->excel->getActiveSheet()->getHighestRow())
    	->getAlignment()->setWrapText(true);
    	$this->excel->getActiveSheet()->getStyle('K1:K'.$this->excel->getActiveSheet()->getHighestRow())
    	->getAlignment()->setWrapText(true);

		//set aligment to center for that merged cell (A1 to D1)
		// $this->excel->getActiveSheet()->getStyle('B1:B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$this->excel->getActiveSheet()->getStyle('B4:B5')->getFont()->setBold(true);

		$filename= 'Laporan Perangkat_'.$date.'.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
			             
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');
	}
}
?>